package freespiritsocial.io.user.ui.fragment.message

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.scwang.smart.refresh.layout.util.SmartUtil
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.chat.ChannelManager
import freespiritsocial.io.user.data.model.bean.PostPojo
import freespiritsocial.io.user.databinding.FrgShareDialogBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.clearData
import freespiritsocial.io.user.ext.dismissLoadingExt
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ext.showLoadingExt
import freespiritsocial.io.user.ui.adapter.CheckPeopleAdapter
import freespiritsocial.io.user.viewmodel.GetMyFollowsViewModel
import freespiritsocial.io.user.viewmodel.SearchFriendViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.base.fragment.BaseBottomSheetDialogFragment
import me.hgj.jetpackmvvm.ext.util.loge
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class SharePostListDialogFragment: BaseBottomSheetDialogFragment() {
    private val getMyFollowsViewModel by activityViewModels<GetMyFollowsViewModel>()
    private val searchViewModel by viewModels<SearchFriendViewModel>()

    companion object {
        const val URL_HOST = "https://admin.freespiritsocial.io/#/freespirit?id="
        const val APP_SHARE_HOST = "https://freespirit.com/ugcdetails/"
        fun crate(parent: BaseFragment<*,*>,post: PostPojo) = SharePostListDialogFragment().apply {
            this.parent = parent
            this.post = post
        }
    }

    private lateinit var parent: BaseFragment<*,*>
    private lateinit var post: PostPojo
    private val adapter by lazy(LazyThreadSafetyMode.NONE) {
        CheckPeopleAdapter()
    }

    private lateinit var mDatabind: FrgShareDialogBinding
    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        mDatabind = DataBindingUtil.inflate(inflater,R.layout.frg_share_dialog,container,false)
        mDatabind.lifecycleOwner = this
        return mDatabind.root
    }

    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        super.onViewCreated(view,savedInstanceState)
        mDatabind.model = searchViewModel
        mDatabind.recycler.init(adapter,emptyImage = R.mipmap.empty_people,emptyText = "No friends have been found yet.")
            .addItemDecoration(SpaceItemDecoration(0,SmartUtil.dp2px(15f)))
        topOffset = SmartUtil.dp2px(50f)
        mDatabind.ivMore.setOnClickListener {
            share()
        }
        //获取关注列表
        lifecycleScope.launch {
            getMyFollowsViewModel.resultFollow.collect {
                adapter.dealData(it)
            }
        }
        mDatabind.tvShare.setOnClickListener {
            sharePost()
        }
        lifecycleScope.launch {
            searchViewModel.searchResultNetWork.collect {
                adapter.addData(it)
            }
        }
        searchViewModel.searchText.observe(this) {
            if (searchViewModel.allData.isEmpty()) searchViewModel.allData.addAll(adapter.data)
            adapter.clearData()
            searchViewModel.search()
        }
    }

    private fun sharePost() {
        showLoadingExt()
        kotlin.runCatching {
            lifecycleScope.launch {
                adapter.selectLis.forEach {
                    "for".loge("csw")
                    val (id,position) = it
                    if (position != -1)
                        withContext(Dispatchers.Default) { sendMessage(id) }
                }
                "end".loge("csw")
                dismissLoadingExt()
                dismiss()
            }
        }.onFailure {
            getMyFollowsViewModel.toast.postValue(it.message)
            dismissLoadingExt()
            dismiss()
        }
    }

    private fun share() {
        val apply = Intent().apply {
            action = Intent.ACTION_SEND
            type = "text/plain"
            putExtra(Intent.EXTRA_TEXT,getShareText())
        }
        startActivity(apply)
    }

    private suspend fun sendMessage(id: String) = suspendCancellableCoroutine<Unit> {
        "sendMessage".loge("csw")
        ChannelManager.createChannel(id) { url,nickName,e ->
            "createChannel".loge("csw")
            if (e != null) it.resumeWithException(e)
            if (url == null || nickName == null) it.resume(Unit)
            ChannelManager.enterChannel(url ?: "") { channel ->
                "enterChannel".loge("csw")
                channel?.sendUserMessage(getAppShareText(),null)
                it.resume(Unit)
            }
        }
    }

    private fun getShareText(): String = post.let {
        it.locationName.toString() + "\n" + it.caption + "\n" + URL_HOST + it.invitationId
    }

    private fun getAppShareText(): String = post.let {
        it.locationName.toString() + "\n" + it.caption + "\n" + APP_SHARE_HOST + it.invitationId + "?scentType=0&nsjeType=1&utm"
    }
}